package com.parkinglot.management.service.impl;

import com.parkinglot.management.repository.AccountRepository;
import com.parkinglot.management.repository.OrderRepository;
import com.parkinglot.management.repository.entity.Account;
import com.parkinglot.management.repository.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Objects;

@Service
public class PayServiceImpl implements PayService {
    @Autowired
    AccountRepository accountRepository;
    @Autowired
    OrderRepository orderRepository;

    @Transactional(isolation = Isolation.REPEATABLE_READ)
    @Override
    public Order payCostByBalance(Order order) {
        Account consumer = accountRepository.findAccountByCarNum(order.getCarNum());
        if (Objects.isNull(consumer)) {
            throw new RuntimeException("该车牌没有登记");
        } else if (consumer.getBalance().compareTo(order.getCost()) == -1) {
            throw new RuntimeException("余额不足");
        } else {
            BigDecimal residue = consumer.getBalance().subtract(order.getCost());
            consumer.setBalance(residue);
            accountRepository.save(consumer);
            order.setStatus(true);
            return orderRepository.save(order);
        }
    }
}
